package com.atguigu.flink.sql.wordcount;

import com.atguigu.flink.func.ClickSource;
import com.atguigu.flink.pojo.Event;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import static org.apache.flink.table.api.Expressions.$;

/**
 * Created by 黄凯 on 2023/6/25 0025 16:49
 *
 * @author 黄凯
 * 永远相信美好的事情总会发生.
 */
public class Flink01_TableAPIWordCount {

    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //读取数据
        DataStreamSource<Event> stream = env.addSource(new ClickSource());

        //将流式执行环境转换成表执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //将流转换成表
        Table table = tableEnv.fromDataStream(stream);

        //打印表结构
        /*
         (
          `user` STRING,
          `url` STRING,
          `ts` BIGINT
         )
         将流转换成表，如果不明确指定Schema,
                流中的数据类型是POJO的情况下， Flink会直接使用POJO的属性名作为表的列名，POJO的属性类型会自动映射成对应的列的类型。
         */
        table.printSchema();

        //基于TableAPI操作
        Table result = table.where($("user").isEqual("Tom"))
                .select($("user"), $("url"), $("ts"));

        //查看表的数据
        result.execute().print();

        try {
            env.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }

}
